package com.telit.uav.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.telit.common.constant.Constant;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.common.util.RedisUtils;
import com.telit.firecommand.dto.DistrictCountDTO;
import com.telit.uav.constant.UavConstant;
import com.telit.uav.dto.CommUavDTO;
import com.telit.uav.dto.UavQueryDTO;
import com.telit.uav.dto.UavTaskDTO;
import com.telit.uav.entity.AppUavTrackDetail;
import com.telit.uav.entity.CommUav;
import com.telit.uav.service.AppUavTrackDetailService;
import com.telit.uav.service.FlightDetailsService;
import com.telit.uav.service.UavQueryService;
import com.telit.uav.vo.UavIsOnlineSumVO;
import com.telit.uav.vo.UavSumVO;
import com.telit.uav.vo.UavVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author zhouyu
 * @description 无人机查询接口
 */
@Api(tags = "02--无人机查询接口", description = "/uav-query")
@RestController
@RequestMapping("/uav-query")
@Slf4j
public class UavQueryController {

    @Autowired
    private UavQueryService uavQueryService;

    @Autowired
    private AppUavTrackDetailService appUavTrackDetailService;

    @Autowired
    private FlightDetailsService flightDetailsService;


    @GetMapping("/queryById")
    @ApiOperation("查询单个无人机信息")
    public DataReturn queryById(@RequestParam(required = true) Long id) {
        try {
            CommUav commUav = uavQueryService.queryById(id);
            if (commUav != null) {
                return DataReturn.ok(commUav);
            } else {
                return DataReturn.failure(ResultCode.BAD_REQUEST, "该无人机设备不存在！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "查询失败！");
        }
    }

    @GetMapping("/queryNameById")
    @ApiOperation("查询无人机名称")
    public DataReturn<String> queryNameById(@RequestParam(required = true) Long id) {
        try {
            String name = uavQueryService.queryNameById(id);
            if (name != null) {
                return DataReturn.ok(name);
            } else {
                return DataReturn.failure(ResultCode.OPERATE_ERROR, "该无人机设备不存在！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "查询失败！");
        }
    }

    @GetMapping("/queryByName")
    @ApiOperation("根据名称或者code查询无人机列表")
    public DataReturn<List<CommUavDTO>> queryByName(@RequestParam(required = false) String uavName) {
        try {
            List<CommUavDTO> commUavs = uavQueryService.queryByName(uavName);
            return DataReturn.ok(commUavs);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR);
        }
    }


    @PostMapping("/cacheUavCameraPosition")
    @ApiOperation("缓存uav监控设备位置")
    public DataReturn cacheUavCameraPosition(@RequestBody List<CommUav> commUavs) {
        try {
            if (commUavs == null) {
                return DataReturn.failure(ResultCode.FORM_PARAMS_CHECK_ERROR);
            }
            RedisUtils.set(UavConstant.UAV_CAMERA_POSITION, JSON.toJSONString(commUavs));
            return DataReturn.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure();
        }
    }

    @GetMapping("/getUavCameraPosition")
    @ApiOperation("获取uav监控设备位置")
    public DataReturn<List<CommUav>> getUavCameraPosition() {
        try {
            List<CommUav> commUavs;
            String cameraInfos = RedisUtils.get(UavConstant.UAV_CAMERA_POSITION);
            if (cameraInfos == null) {
                commUavs = uavQueryService.queryPositionCamera();
                cameraInfos = JSON.toJSONString(commUavs);
                RedisUtils.set(UavConstant.UAV_CAMERA_POSITION, cameraInfos);
            } else {
                commUavs = JSONObject.parseArray(cameraInfos, CommUav.class);
            }
            return DataReturn.ok(commUavs);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure();
        }
    }


    //查询行政区划内的无人机数量(单独数量不包含详情)
    @ApiOperation("01--根据code，在离线状态查询无人机列表,不传参数表示查询所有 isOnline=0离线 1 在线 ")
    @GetMapping("/queryByIsOnlineSum")
    public DataReturn<UavSumVO> queryByIsOnlineSum(@RequestParam(required = false) String uavCode,
                                                   @RequestParam(required = false) Integer isOnline,
                                                   @RequestParam(required = false) String cityCode,
                                                   @RequestParam(required = false) Integer isFlying) {

        UavSumVO data = uavQueryService.queryByIsOnlineSum(uavCode, isOnline, cityCode, isFlying);
        return DataReturn.ok(data);
    }

    //根据城市code查询下面对应无人机数据
    @ApiOperation("02--根据城市code查询下面对应无人机数据")
    @GetMapping("/queryUavByCityCode")
    public DataReturn<List<UavIsOnlineSumVO>> queryUavByCityCode(@RequestParam(required = false) String uavCode,
                                                                 @RequestParam(required = false) Integer isOnline,
                                                                 @RequestParam(required = false) String cityCode,
                                                                 @RequestParam(required = false) Integer isFlying) {

        List<UavIsOnlineSumVO> data = uavQueryService.queryUavByCityCode(uavCode, isOnline, cityCode, isFlying);
        return DataReturn.ok(data);
    }


    //根据无人机id查询对应的无人机信息
    @ApiOperation("03--根据无人机id查询对应的无人机信息 ")
    @GetMapping("/queryUavById")
    public DataReturn<UavVO> queryUavById(@RequestParam(required = false) Long id) {
        UavVO data = uavQueryService.queryUavById(id);
        return DataReturn.ok(data);
    }


    /**
     * 根据在离线状态查询无人机列表
     *
     * @param isOnline
     *
     * @return
     */
    @GetMapping("/queryByIsOnline")
    @ApiOperation("根据无人机名称，在离线状态查询无人机列表,不传参数表示查询所有")
    public DataReturn queryByCondition(@RequestParam(required = false) String uavCode,
                                       @RequestParam(required = false) Integer isOnline,
                                       @RequestParam(required = false) Integer isFlying) {
        try {
            List<UavTaskDTO> data = uavQueryService.queryByCondition(uavCode, isOnline, isFlying);
            return DataReturn.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "查询失败！");
        }
    }


    @GetMapping("/querySubTaskNumber")
    @ApiOperation("根据不同状态查询子任务数量")
    public DataReturn querySubTaskNumber(@RequestParam Long taskId, @RequestParam String status) {
        try {
            if (StringUtils.isEmpty(taskId)) {
                log.warn("根据不同状态查询子任务数量querySubTaskNumber:参数taskId为空！");
                return DataReturn.failure(ResultCode.OPERATE_ERROR, "参数taskId为空！");
            }
            if (StringUtils.isEmpty(status)) {
                log.warn("根据不同状态查询子任务数量querySubTaskNumber:参数status为空！");
                return DataReturn.failure(ResultCode.OPERATE_ERROR, "参数status为空！");
            }
            Long data = uavQueryService.querySubTaskNumber(taskId, status);
            return DataReturn.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "查询失败！");
        }
    }

    @GetMapping("/queryDelayNumber")
    @ApiOperation("查询逾期任务数量")
    public DataReturn queryDelayNumber(@RequestParam(required = true) Long taskId,
                                       @RequestParam(required = false) Date endTime) {
        try {
            Long data = uavQueryService.queryDelayNumber(taskId, endTime);
            return DataReturn.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR, "查询失败！");
        }
    }


    @GetMapping("/queryCruisePointCollection")
    @ApiOperation("查询轨迹")
    public DataReturn queryCruisePointCollection(@RequestParam("taskId") Long taskId,
                                                 @RequestParam("userId") Long userId) {
        String data = uavQueryService.queryCruisePointCollection(taskId, userId);
        return DataReturn.ok(data);
    }

    @GetMapping("/queryListMap")
    @ApiOperation("查询所有无人机信息，返回List<Map<String,Object>>")
    public DataReturn queryListMap() {
        List<Map<String, Object>> listMap = uavQueryService.selectListMap();
        return DataReturn.ok(listMap);
    }

    @GetMapping("/queryUavFlyDetailBySubTaskId")
    @ApiOperation("查询飞行实时轨迹信息")
    public DataReturn<List<AppUavTrackDetail>> queryUavFlyDetailBySubTaskId(@RequestParam("taskId") Long subTaskId) {
        List<AppUavTrackDetail> data = appUavTrackDetailService.queryUavFlyDetailBySubTaskId(subTaskId);
        return DataReturn.ok(data);
    }

    @GetMapping("/getUnOnlineUavInfo")
    @ApiOperation("无人机巡航首页离线无人机信息")
    public DataReturn<UavTaskDTO> getUnOnlineUavInfo(@RequestParam String uavCode) {
        UavTaskDTO uavTaskDTO = uavQueryService.getUnOnlineUavInfo(uavCode);
        return DataReturn.ok(uavTaskDTO);
    }

    @GetMapping(value = "/uavCount", produces = "application/json;charset=UTF-8")
    @ApiOperation("无人机数量")
    public DataReturn uavCount(@RequestParam(required = false) Integer isFlying) {
        return DataReturn.ok(uavQueryService.uavCount(isFlying));
    }

    @GetMapping(value = "/listUavProducter", produces = "application/json;charset=UTF-8")
    @ApiOperation("查询所有无人机设备厂商")
    public DataReturn listUavProducter() {
        return DataReturn.ok(uavQueryService.listUavProducter());
    }

    @GetMapping(value = "/getUavModelByProId", produces = "application/json;charset=UTF-8")
    @ApiOperation("根据设备厂家Id查询无人机型号")
    public DataReturn getUavModelByProId(@RequestParam Long ProducterId) {
        return DataReturn.ok(uavQueryService.getUavModelByProId(ProducterId));
    }

    @GetMapping("/flyDetail/{userId}/{taskId}")
    @ApiOperation("查看某一任务无人机飞行详情")
    public DataReturn flyingDetail(@PathVariable("userId") Long userId, @PathVariable("taskId") Long taskId) {
        List<AppUavTrackDetail> list = flightDetailsService.queryTrackDetail(taskId, userId);
        return DataReturn.ok(CollectionUtils.isEmpty(list) ? null : list.get(0));
    }


    @GetMapping("/querySimpleDataByCondition")
    @ApiOperation("根据经纬度、半径查询无人机指定列表")
    public DataReturn<List<UavVO>> queryByCondition(@RequestParam(value = "radius") String radius,
                                                    @RequestParam(value = "longitude") String longitude,
                                                    @RequestParam(value = "latitude") String latitude,
                                                    @RequestParam(required = false, value = "flag") String flag) {
        try {
            List<UavVO> simpleCommUavDtoList = uavQueryService.querySimpleDataByCondition(radius, longitude, latitude,
                    flag);
            return DataReturn.ok(simpleCommUavDtoList);
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.OPERATE_ERROR);
        }
    }

    //根据行政区划代码查询无人机
    @ApiOperation(" 分页条件查询无人机列表")
    @GetMapping("/listUavByPage")
    public DataReturn listUavByPage(@RequestParam(defaultValue = "1") Integer current,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    UavQueryDTO uavQueryDTO) {

        IPage<UavVO> uavIPage = uavQueryService.listUavByPage(current, size, uavQueryDTO);
        return DataReturn.ok(new PageData<>((int) uavIPage.getTotal(), current, size, uavIPage));
    }

    @GetMapping(value = "/listUavToken", produces = "application/json;charset=UTF-8")
    @ApiOperation("查询无人机token")
    public DataReturn listUavToken() {
        return DataReturn.ok(uavQueryService.listUavToken());
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "isOnline", value = "在线  1在线 0离线", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "uavName", value = "名称（模糊查询）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "districtCode", value = "行政区划", required = true, paramType = "query", dataType = "String"),
    })
    @GetMapping(value = "/qry-num-by-parent-code")
    @ApiOperation(value = "根据父行政区划编码查询数量，初始化时请传递省份code（安徽省：34）", httpMethod = Constant.REQUEST_METHOD_GET)
    public DataReturn<DistrictCountDTO> qryNumByParentCode(
            @RequestParam(value = "isOnline", required = false) Integer isOnline,
            @RequestParam(value = "uavName", required = false) String uavName,
            @RequestParam(value = "districtCode") String districtCode) {
        return DataReturn.ok(uavQueryService.qryNumByParentCode(isOnline, uavName, districtCode));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "isOnline", value = "在线  1在线 0离线", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "uavName", value = "名称（模糊查询）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "districtCode", value = "行政区划", required = true, paramType = "query", dataType = "String"),
    })
    @GetMapping(value = "/qry-district-list-by-parent-code")
    @ApiOperation(value = "根据父行政区划编码查询子类集合，初始化时请传递省份code（安徽省：34）", httpMethod = Constant.REQUEST_METHOD_GET)
    public DataReturn<DistrictCountDTO> qryDistrictListByParentCode(
            @RequestParam(value = "isOnline", required = false) Integer isOnline,
            @RequestParam(value = "uavName", required = false) String uavName,
            @RequestParam(value = "districtCode") String districtCode) {
        return DataReturn.ok(uavQueryService.qryDistrictListByParentCode(isOnline, uavName, districtCode));
    }

}
